package services

import (
	"bytes"
	"encoding/binary"
	"strconv"

	"github.com/labstack/echo/v4"
)

// receiveDataFromDACHandler websocket获取数据采集卡的数据
func receiveDataFromDACHandler(c echo.Context) error {
	name := c.Param("dacName")
	port, err := strconv.Atoi(c.QueryParam("port"))
	if err != nil {
		return badRequest("port转换为数字失败, 错误：" + err.Error())
	}
	unit := c.QueryParam("unit")
	samplesPerSecond, err := strconv.Atoi(c.QueryParam("samplesPerSecond"))
	if err != nil {
		return badRequest("samplesPerSecond转换为数字失败, 错误：" + err.Error())
	}

	if dacDataMap.isConnected(name) {
		return forbidden("采集卡'" + name + "'已经连接！请检查采集卡名称是否重复")
	}

	// 记录该采集卡已经连接数据中心服务器
	dacDataMap.setConnectionStatus(name, true)

	dacDataMap.setBasicInfo(name, c.RealIP(), port, unit, samplesPerSecond)

	ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
	if err != nil {
		return err
	}
	defer func() {
		// 断开连接后的清理
		dacDataMap.setConnectionStatus(name, false)
		ws.Close()
	}()

	for {
		_, msg, err := ws.ReadMessage()
		if err != nil {
			c.Logger().Error(err)
			return err
		}

		var data sampleData
		if err := binary.Read(bytes.NewReader(msg), binary.LittleEndian, &data); err != nil {
			c.Logger().Error("binary.Read failed in receiveDataFromDAC: ", err)
			continue
		}

		dacDataMap.appendSample(name, data)
	}
}
